#include "clientcurrentplaylistdialog.h"
#include "ui_clientcurrentplaylistdialog.h"
#include "datacenter.h"
#include "common.h"
#include "playlistcenter.h"
#include "singleclient.h"

ClientCurrentPlayListDialog::ClientCurrentPlayListDialog(boost::shared_ptr<SingleClient>client, QWidget *parent):
    QDialog(parent),
	ui(new Ui::ClientCurrentPlayListDialog),
	m_Client(client)
{
    ui->setupUi(this);
	setupWidgets();
	setupTimer();
}

void ClientCurrentPlayListDialog::setupWidgets()
{
	PlayListCenter* playListCenter = g_DataCenter->createPlayListCenter();
	PlayList playList;
	playListCenter->getNewestPlayList(m_Client->getId(), playList);

	ui->m_PlayList->setEditTriggers(QAbstractItemView::NoEditTriggers);
	ui->m_PlayList->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->m_PlayList->setSelectionMode(QAbstractItemView::SingleSelection);

	for(size_t i = 0; i < playList.size(); ++i)
	{
		int rowCount = ui->m_PlayList->rowCount();
		const VideoFileInformation& info = playList[i];
		ui->m_PlayList->insertRow(rowCount);

		ui->m_PlayList->setItem(rowCount, 0, new QTableWidgetItem(info.m_StartTime.toString("hh:mm")));
		ui->m_PlayList->setItem(rowCount, 1, new QTableWidgetItem(info.m_EndTime.toString("hh:mm")));
		ui->m_PlayList->setItem(rowCount, 2, new QTableWidgetItem(info.m_FileName));
	}
	timeToRefresh();
}

void ClientCurrentPlayListDialog::setupTimer()
{
	QTimer* timer = new QTimer(this);
	timer->setInterval(10000);
	connect(timer, SIGNAL(timeout()), this, SLOT(timeToRefresh()));
	timer->start();
}

void ClientCurrentPlayListDialog::timeToRefresh()
{
	QTime currentTime = QTime::currentTime();
	for(int rowIndex = 0; rowIndex < ui->m_PlayList->rowCount(); ++rowIndex)
	{
		QTime startTime = QTime::fromString(ui->m_PlayList->item(rowIndex, 0)->text(), "hh:mm");
		QTime endTime = QTime::fromString(ui->m_PlayList->item(rowIndex, 1)->text(), "hh:mm");
		if(startTime <= currentTime && currentTime <= endTime)
		{
			for(int colIndex = 0; colIndex < 3; ++colIndex)
			{
				ui->m_PlayList->item(rowIndex, colIndex)->setTextColor(Qt::blue);
			}
		}
		else
		{
			for(int colIndex = 0; colIndex < 3; ++colIndex)
			{
				ui->m_PlayList->item(rowIndex, colIndex)->setTextColor(Qt::black);
			}
		}
	}
}

ClientCurrentPlayListDialog::~ClientCurrentPlayListDialog()
{
    delete ui;
}

void ClientCurrentPlayListDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
